/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the Clear BSD license. 
* See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
	
/**
* @requires OpenLayers/Protocol.js
*/

/**
* Class: OpenLayers.Protocol.BroswerStorage
* Class for access to SQL Web Storage or Web (local) Storage.
* Allows you to store, retrieve and get information about what
* is stored.
*
* Inherits from:
*  - <OpenLayers.Protocol>
*/
OpenLayers.Protocol.BrowserStorage = OpenLayers.Class(OpenLayers.Protocol, {   
	initialize: function(name, version, description, size) {
	        var store;
	        // Default to Web SQL Storage
	        try {
	            store = this.sqlStore; 
	            return store.initialize(name, version, description, size);
	        } catch (e) {
	            /* Does not support Web SQL Storage */
	        }
	       
	        // Use Web (Local) Storage if Web SQL not available.
	        try {
	            store = this.localStore;
	            return store.initialize(name, version, description, size);
	           
	        } catch (e) {           
	            /* Does not support Web (local) Storage */
	            // TODO Throw an error
	            console.debug(e);
	        }
	         
	    },
	   
	  /* localStore ****************************************************************/
	
	  localStore: {
	       
	    name:null,
	    version:null,
	    description:null,
	    size:null,
	       
	    initialize: function(name, version, description, size) {
	        if (localStorage) {       
	          this.name = name;
	          this.version = version;
	          this.description = description;
	          this.size = size;
	        } else {
	            throw new Error("Local storage is not supported.");
	        }
	        return this;
	    },
	    set: function(key, value) {
	        try {
	            localStorage.setItem(key,value);
	        } catch (e) {
	            if((e.name).toUpperCase() == 'QUOTA_EXCEEDED_ERR') {
	              //TODO Replace with correct error handling.
	              alert ("Unable to cache area, cache is full.");
	            }
	        }
	    },
	    get: function(key) {
	        return localStorage.getItem(key);
	    },
	    clear: function() {
	        localStorage.clear();
	    },
	    count: function(resultHandler) {       
	        resultHandler("LocalStorage", localStorage.length);
	    }
	  },
	
	  /* sqlStore ******************************************************************/
	
	  sqlStore: {
	   
	    name:null,
	    version:null,
	    description:null,
	    size:null,
	    db: null,
	         
	    initialize: function(name, version, description, size) {
	        try {
	          this.name = name;
	          this.version = version;
	          this.description = description;
	          this.size = size;
	          this.db = openDatabase(name, version, description, size);
	         
	          this.db.transaction(
	            function(tx) {
	                tx.executeSql("Create table OLTable (key TEXT, value BLOB) ",
	                [],
	                function(tx, result) {
	                    /* No results  */
	                }, function(tx, error) {
	                    /* table may already exist */
	                    console.debug(error);
	                });
	          });
	         
	        } catch (e) {
	            throw new Error("Web SQL storage is not supported.");
	        }
	        return this;
	
	    },
	    set: function(key, value) {
	        var name = this.name;
	        // TODO Check for existing entries to prevent duplicates.
	        this.db.transaction(
	            function(tx) {
	                tx.executeSql("Insert into OLTable (key, value) values (?,?)",
	                [key,value],
	                function(tx, result) {
	                    /* No results as it's an insert */
	                }, function(tx, error) {
	                    console.debug(error);
	                });
	        });
	    },
	    get: function(key) {
	        var name = this.name;
	        this.db.transaction(
	            function(tx) {
	                console.log("Select value from OLTable where key=?");
	                tx.executeSql("Select value from OLTable where key=?",
	                [key],
	                function(tx, result) {
	                  if(result.rows.length){
	                    return result.rows.item(0).data;
	                  }
	                }, function(tx, error) {
	                    console.debug(error);
	                });
	        });
	    },
	   
	    clear: function() {
	        this.db.transaction(
	                function(tx) {
	                    tx.executeSql("Delete from OLTable",
	                    [],
	                    function(tx, result) {
	                        /* No results */
	                    }, function(tx, error) {
	                        console.debug(error);
	                    });
	            });
	    },
	    count: function(resultHandler) {
	
	        var count;
	        var name = this.name;
	        this.db.transaction(
	                function(tx) {
	                    console.log("Select count(*) as count from OLTable");
	                    tx.executeSql("Select count(*) as count from OLTable",
	                    [],
	                    function(tx, result) {
	                      if(result.rows.length){                       
	                         resultHandler(name,result.rows.item(0)['count']);
	                      }
	                    }, function(tx, error) {
	                        console.debug(error);
	                    });
	            },
	            function(tx, result) {
	                console.debug(tx);
	                }, function(tx, error) {
	                    console.debug(tx);
	                });
	    }
	  },
	
	  CLASS_NAME: "OpenLayers.Protocol.BrowserStorage"
	});